package com.naihe.anderson.sms.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.Geoloc;
import com.naihe.anderson.sms.util.FileUtil;
import com.naihe.anderson.sms.util.HttpUtil;

public class MapViewActivity extends MapActivity implements OnClickListener {
	private MapView mMapView;
	private MapController mMapController;
	private GeoPoint mGeoPoint;
	private LocationManager locationMgr;
	private Location location;
	private TextView tip;
    private String tipTemp="";
	private ProgressBar progressBar;
	private ImageButton locationHere;
	private FrameLayout locaion_arrow_tips_ll;
	private boolean isMoved = false;
	private Geoloc geoloc;
	private int iAutoUpdateFrequency = 500;
	private NhSmsApp nhSmsApp;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location_map_google);
		nhSmsApp = (NhSmsApp) getApplication();
		nhSmsApp.setActivity(this);
		Button backBtn = (Button) findViewById(R.id.map_back_btn);
		Button sentBtn = (Button) findViewById(R.id.map_sent_btn);
		tip = (TextView) findViewById(R.id.location_tips);
		progressBar = (ProgressBar) findViewById(R.id.location_load_progress);
		locationHere = (ImageButton) findViewById(R.id.location_here);
		locaion_arrow_tips_ll = (FrameLayout) findViewById(R.id.locaion_arrow_tips_ll);

		backBtn.setOnClickListener(this);
		sentBtn.setOnClickListener(this);

		locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		if (locationMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			locationMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, iAutoUpdateFrequency, 0,
					locationListener);
			location = locationMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		} else {
			// Settings.Secure.setLocationProviderEnabled(getContentResolver(),
			// LocationManager.NETWORK_PROVIDER, true);
		}

		mMapView = (MapView) findViewById(R.id.g_mapView);
		mMapView.setBuiltInZoomControls(true);

		mMapController = mMapView.getController();

		if (location != null) {
			mGeoPoint = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
			mMapController.animateTo(mGeoPoint);

        } else if (!locationMgr.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER) && !locationMgr
                .isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.open_local_server).setCancelable(false)
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    }).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 0);
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }

		// (1-21)
		mMapController.setZoom(18);
		new MyAsyncTask().execute(mGeoPoint);
	}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (locationMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                locationMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, iAutoUpdateFrequency, 0, locationListener);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location2) { // 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
			// log it when the location changes
			if (location2 != null) {
				FileUtil.addLog("Location changed : Lat: " + location2.getLatitude() + " Lng: " + location2.getLongitude(), MapViewActivity.class, "MapViewActivity", null);
                if (location == null) {
                    location = location2;
                    mGeoPoint = new GeoPoint((int) (location2.getLatitude() * 1E6), (int) (location2.getLongitude() * 1E6));
                    mMapController.animateTo(mGeoPoint);
                    new MyAsyncTask().execute(mGeoPoint);
                }
			}
		}

		public void onProviderDisabled(String provider) {
			// Provider被disable时触发此函数，比如GPS被关闭
		}

		public void onProviderEnabled(String provider) {
			// Provider被enable时触发此函数，比如GPS被打开
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
		}
	};

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		int action = ev.getAction();
		switch (action) {
		case MotionEvent.ACTION_MOVE:
			if (!isMoved) {
				isMoved = true;
				locaion_arrow_tips_ll.setVisibility(View.GONE);
			}
			break;
		case MotionEvent.ACTION_UP:
			if (isMoved) {
				isMoved = false;
				TranslateAnimation animation = new TranslateAnimation(0, 0, 100, 0);
				animation.setDuration(400);
				animation.setFillAfter(true);
				locationHere.startAnimation(animation);

				locaion_arrow_tips_ll.setVisibility(View.VISIBLE);
				progressBar.setVisibility(View.VISIBLE);
				tip.setText("");

				int[] location = new int[2];
				locationHere.getLocationInWindow(location);
				Projection proj = mMapView.getProjection();
				GeoPoint loc = proj.fromPixels(location[0], location[1]);
				if (geoloc == null)
					geoloc = new Geoloc();
				geoloc.setLat(loc.getLatitudeE6() / 1E6);
				geoloc.setLon(loc.getLongitudeE6() / 1E6);
				new MyAsyncTask().execute(loc);
			}
			break;
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public void onClick(View view) {
		if(view.getId() == R.id.map_sent_btn){
			if (geoloc == null) {
				geoloc = new Geoloc();
				geoloc.setLat(location.getLatitude());
				geoloc.setLon(location.getLongitude());
			}
            geoloc.setCountry(tipTemp);
            //-----------
            Intent intent = new Intent(MapViewActivity.this, NewExpenditureActivity.class);
            intent.putExtra("geoloc", geoloc);
			this.setResult(RESULT_OK, intent);
			toFinishActivity();
		} else if(view.getId() == R.id.map_back_btn){
			toFinishActivity();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			toFinishActivity();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void toFinishActivity(){
		nhSmsApp.setActivity(null);
		MapViewActivity.this.finish();
		System.gc();
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	private class MyAsyncTask extends AsyncTask<GeoPoint, Object, String> {
		@Override
		protected String doInBackground(GeoPoint... objects) {
			if (objects[0] == null)
				return "";
			GeoPoint geoPoint = (GeoPoint) objects[0];
			return HttpUtil.getAddressInfo(geoPoint.getLatitudeE6()/1E6 + "," + geoPoint.getLongitudeE6() / 1E6);
		}

		@Override
		protected void onPostExecute(String o) {
			tip.setText(o.toString());
            tipTemp = o.toString();
			progressBar.setVisibility(View.INVISIBLE);
		}
	}

}
